package com.wanglibao.woodtrade.woodtrade.model.impl;

import android.content.Context;

import com.google.gson.Gson;
import com.wanglibao.woodtrade.woodtrade.model.WoodType;
import com.wanglibao.woodtrade.woodtrade.model.WoodTypeDetail;
import com.wanglibao.woodtrade.woodtrade.model.WoodTypeDetailThreePlace;
import com.wanglibao.woodtrade.woodtrade.model.db.BaseDao;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by lugg on 2016/5/10.
 */
public class WoodTypeImpl extends BaseDao<WoodType,String> {
    public WoodTypeImpl(Context context) {
        super(context, WoodType.class);
    }

    public static void analyWoodType(Context context, String json) {
        List<WoodType> woodTypes = new ArrayList<>();
        List<WoodTypeDetail> woodTypeDetails = new ArrayList<>();
        List<WoodTypeDetailThreePlace> woodTypeDetailThreePlaces = new ArrayList<>();
        Gson gson = new Gson();
        try {
            JSONObject jsonObject = new JSONObject(json);
            JSONArray jsonArray = jsonObject.getJSONArray("list");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                WoodType woodType = gson.fromJson(jsonObject1.toString(), WoodType.class);
                woodTypes.add(woodType);
                JSONArray jsonArray1 = jsonObject1.getJSONArray("child");
                for (int j = 0; j < jsonArray1.length(); j++) {
                    JSONObject jsonObject2 = jsonArray1.getJSONObject(j);
                    WoodTypeDetail woodTypeDetail = gson.fromJson(jsonObject2.toString(), WoodTypeDetail.class);
                    woodTypeDetails.add(woodTypeDetail);
                    JSONArray jsonArray2 = jsonObject2.getJSONArray("child");
                    for (int z = 0; z < jsonArray2.length(); z++){
                        JSONObject jsonObject3 = jsonArray2.getJSONObject(z);
                        WoodTypeDetailThreePlace woodTypeDetailThreePlace = gson.fromJson(jsonObject3.toString(), WoodTypeDetailThreePlace.class);
                        woodTypeDetailThreePlaces.add(woodTypeDetailThreePlace);
                    }
                }
            }
            WoodTypeImpl woodTypeImpl = new WoodTypeImpl(context);
            woodTypeImpl.deleteAll();
            woodTypeImpl.insertWithTransaction(woodTypes);
            WoodTypeDetailImpl woodTypeDetailImpl = new WoodTypeDetailImpl(context);
            woodTypeDetailImpl.deleteAll();
            woodTypeDetailImpl.insertWithTransaction(woodTypeDetails);
            WoodTypeDetailThreePlaceImpl woodTypeDetailThreePlace = new WoodTypeDetailThreePlaceImpl(context);
            woodTypeDetailThreePlace.deleteAll();
            woodTypeDetailThreePlace.insertWithTransaction(woodTypeDetailThreePlaces);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

}
